<template>
  <div class="publish-box" v-loading="loading">
    <el-steps :active="activestep" finish-status="success" process-status="process"	simple>
      <el-step title="1.编辑基本信息" ></el-step>
      <el-step title="2.编辑商品详情" ></el-step>
    </el-steps>
    <!--步骤1-->
    <div class="content-goods-publish" v-show="activestep === 0">
      <!--商品详情-->
      <el-form
        :model="baseInfoForm"
        status-icon
        :rules="baseInfoFormRule"
        label-position="right"
        ref="baseInfoForm"
        label-width="120px"
        class="demo-ruleForm">
        <!--商品类型-->
        <div class="base-info-item">
          <h4>商品类型</h4>
          <div class="pro-type-row">
            <el-form-item class="auth-info" label="拒绝原因" v-if="baseInfoForm.is_auth === 2">
              {{ baseInfoForm.auth_message }}
            </el-form-item>
            <el-form-item label-width="0" prop="goods_type">
              <el-radio-group class="box-radio" v-model="baseInfoForm.goods_type">
                <el-radio :label="0" border>
                  <div class="radio-name">实物商品</div>
                  <div class="radio-tip">（物流发货）</div>
                </el-radio>
                <el-radio :label="1" border>
                  <div class="radio-name">虚拟商品</div>
                  <div class="radio-tip">（无需物流）</div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <!--基本信息-->
        <div class="base-info-item">
          <h4>基本信息</h4>
          <div>
            <el-form-item label="商品名称" prop="goods_name" class="goods-name-width">
              <el-input v-model="baseInfoForm.goods_name" @change="() => { baseInfoForm.goods_name = baseInfoForm.goods_name.trim() }" :maxlength="60" :minlength="3" placeholder="3-60个字符"></el-input>
            </el-form-item>
            <el-form-item label="商品卖点" prop="selling" class="goods-selling-width">
              <el-input v-model="baseInfoForm.selling" @change="() => { baseInfoForm.selling = baseInfoForm.selling.trim() }" :maxlength="60" :minlength="3" placeholder="3-60个字符"></el-input>
            </el-form-item>
            <el-form-item label="商品图片" ref="goods_gallery" prop="goods_gallery" style="width: 90%;">
              <upload-sortable
                class="avatar-uploader goods-images"
                :goodsGalleryList='goodsGalleryList'
                @click="handlePictureClick"
                @change="handlePictureChange">
              </upload-sortable>
              <el-dialog :visible.sync="dialogImage">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <el-form-item label="主图视频" ref="video_url" prop="video_url" style="width: 90%;">
              <div class="video_box">
                <el-upload
                  ref="video_url"
                  class="img-upload upload-video"
                  :action="MixinUploadApi"
                  :on-success="(res) => { uploadVideo(res)}"
                  :before-upload="beforeUploadVideo"
                  :show-file-list="false"
                  :on-progress="onProgress">
                  <div v-if="!baseInfoForm.video_url" class="img_none">
                    <el-progress v-if="video_ico" type="circle" :percentage="percentage" class="progress"></el-progress>
                    <i class="el-icon-upload2"></i>
                    <div class="upload-tip">上传视频</div>
                  </div>
                  <video v-else class="avatar video-avatar"
                    controls="controls"
                    align="center"
                    :src="baseInfoForm.video_url">
                    您的浏览器不支持视频播放
                  </video>
                </el-upload>
                <span v-if="baseInfoForm.video_url" class="delet-list-item" @click="removeVideo()"><i class="el-icon-close"></i></span>
              </div>
              <div class="row-tip">目前仅支持在手机端播放，建议时长9-30</div>
            </el-form-item>
            <el-form-item label="商品品类" style="width: 90%;" prop="category_id">
              <el-input v-show="false" type="hidden" v-model="baseInfoForm.category_id"></el-input>
              <div v-if="!baseInfoForm.category_id" class="category-none" @click="showCategory()">选择商品品类</div>
              <div v-else class="category-show">
                <span>{{ activeCategoryName1 }}</span>
                <span v-show="activeCategoryName2"> > {{ activeCategoryName2 }}</span>
                <span v-show="activeCategoryName3"> > {{ activeCategoryName3 }}</span>
                <span v-if="!activeCategoryName1" v-html="baseInfoForm.category_name"></span>
                <span  class="link-btn" @click="showCategory(baseInfoForm.category_id)">修改品类</span>
              </div>
              <div class="row-tip">
                <span>准确选择商品品类可以更方便用户基于分类检索到您的商品</span>
                <el-popover
                  placement="top"
                  width="350"
                  trigger="hover">
                  <div class="popover-head">选择商品品类在分类中显示示例</div>
                  <img class="popover-img" src="../../assets/ej-category.png" />
                  <span class="link-btn" slot="reference">查看示例</span>
                </el-popover>
              </div>
            </el-form-item>
            <el-form-item label="商品分组" style="width: 100%;" prop="shop_cat_id">
              <!--商品分组 获取分类列表 传入默认值-->
              <en-category-picker @changed="changeGoodsCateGory" :clearable='true'
                :defaultVal="baseInfoForm.shop_cat_id" />
              <div class="row-tip">
                <span>商品可以从属于店铺的某个分组之下，店铺分组可以由 "商家中心 -> 商品管理 -> 分组管理" 中自定义</span>
                <el-popover
                  placement="top"
                  width="350"
                  trigger="hover">
                  <div class="popover-head">选择商品分组在店铺首页显示示例</div>
                  <img class="popover-img" src="../../assets/ej-group.png" />
                  <span class="link-btn" slot="reference">查看示例</span>
                </el-popover>
              </div>
            </el-form-item>
            <el-form-item label="商品品牌" prop="brand_id">
              <el-select
                v-model="baseInfoForm.brand_id"
                filterable
                @change="changeGoodsBrand"
                clearable
                placeholder="请选择">
                <el-option
                  v-for="item in brandList"
                  :key="item.brand_id"
                  :label="item.name"
                  :value="item.brand_id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商">
              <el-input style="width: 185px;" v-model="baseInfoForm.supplier_name" placeholder="来自供应商资料" clearable></el-input>
            </el-form-item>
            <el-form-item label="贮存方式" prop="store" v-if="baseInfoForm.goods_type !== 1">
              <dg-select style="width: 185px;" v-model="baseInfoForm.store" dictType="store_type" placeholder="请选择贮存方式" :defaultValue="baseInfoForm.store" clearable></dg-select>
            </el-form-item>
            <el-form-item label="分拣类型" prop="pre_sort" v-if="baseInfoForm.goods_type !== 1">
              <el-radio-group v-model="baseInfoForm.pre_sort"  style="display:flex">
                <el-radio :label="0">无需预分拣</el-radio>
                <el-radio :label="1">需要预分拣</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="外部商品ID">
              <el-input style="width: 185px;" v-model="baseInfoForm.up_goods_id"  placeholder="供应商的商品ID" clearable></el-input>
            </el-form-item>
            <!-- <el-form-item label="过期时间" prop="expiry_day" v-if="baseInfoForm.goods_type === 1">
              <dg-select v-model="baseInfoForm.expiry_day" dictType="expiry_date" placeholder="请选择过期时间" :defaultValue="baseInfoForm.expiry_day" clearable></dg-select>
            </el-form-item> -->
          </div>
        </div>
        <!--价格库存-->
        <div class="base-info-item">
          <h4>价格库存</h4>
          <div>
            <el-form-item label="商品价格" prop="price">
              <el-input style="width: 200px;" placeholder="请输入商品价格" v-model="baseInfoForm.price" :maxlength="10">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
            <el-form-item label="市场价格" prop="mktprice" style="width: 90%;">
              <el-input style="width: 200px;" placeholder="请输入市场价格" v-model="baseInfoForm.mktprice" :maxlength="10">
                <template slot="prepend">¥</template>
              </el-input>
              <div class="row-tip">
                <span>商品没有优惠的情况下，划线价在商品详情会以划线形式显示</span>
                <el-popover
                  placement="top"
                  width="350"
                  trigger="hover">
                  <div class="popover-head">市场价在商品详情中显示示例</div>
                  <img class="popover-img" src="../../assets/ej-price.png" />
                  <span class="link-btn" slot="reference">查看示例</span>
                </el-popover>
              </div>
            </el-form-item>
            <!-- <el-form-item label="截止日期" v-if="baseInfoForm.goods_type" :rules="baseInfoForm.goods_type === 1 ? {required: true, message: '截止日期不能为空', trigger: 'change' } : {}">
              <dg-select style="width: 185px;" v-model="baseInfoForm.expiryDay" dictType="expiry_date" placeholder="虚拟商品的使用截止日期" :defaultValue="baseInfoForm.expiryDay" clearable></dg-select>
            </el-form-item> -->
            
            <el-form-item label="截止日期" prop="expiry_day" v-if="baseInfoForm.goods_type">
              <dg-select v-model="baseInfoForm.expiry_day" dictType="expiry_date" placeholder="请选择过期时间" :defaultValue="baseInfoForm.expiry_day" clearable></dg-select>
            </el-form-item>
            <el-form-item label="可用日期" prop="available_date" style="width: 90%;text-align: left;" v-if="baseInfoForm.goods_type">
              <div class="checkWeekTime">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="baseInfoForm.available_date" @change="handleCheckedWeekTimeChange">
                  <el-checkbox v-for="timer in weekTime" :label="timer" :key="timer">{{timer}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
            <el-form-item label="商品规格"  style="width: 90%;text-align: left;">
              <!--规格选择器-->
              <en-sku-selector
                :categoryId="baseInfoForm.category_id"
                :goodsId="activeGoodsId"
                :goodsSn="baseInfoForm.sn"
                :productSn="productSn"
                :isEditModel="currentStatus"
                :goodsSkuInfo="skuList"
                @finalSku="finalSku"/>
            </el-form-item>
            <el-form-item label="总库存" :prop="currentStatus === 0 ? 'quantity' : ''" style="width: 20%;text-align: left;">
              <el-input v-model.number="baseInfoForm.quantity" :disabled="currentStatus === 1 || isEditQuantity"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight" :maxlength="10">
              <el-input placeholder="请输入商品重量" v-model="baseInfoForm.weight" step="0.001"  min="0" onkeyup="this.value= this.value.match(/\d+(\.\d{0,3})?/) ? this.value.match(/\d+(\.\d{0,3})?/)[0] : ''">
                <template slot="prepend">kg</template>
              </el-input>
            </el-form-item>
            <!-- <el-form-item label="商品编码" prop="sn">
              <el-input v-model="baseInfoForm.sn" :maxlength="20"></el-input>
            </el-form-item> -->
            <el-form-item label="成本价格" prop="cost" :maxlength="10">
              <el-input placeholder="请输入成本价格" v-model="baseInfoForm.cost">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <!--物流/其他-->
        <div v-if="baseInfoForm.goods_type===0" class="base-info-item">
          <h4>物流/其他</h4>
          <!-- <div>
            <el-form-item label="运费" style="width: 50%;" prop="template_id">
              <el-radio-group v-model="baseInfoForm.goods_transfee_charge" @change="changeTplItem">
                <el-radio :label="1">卖家承担运费</el-radio>
                <el-radio :label="0">买家承担运费</el-radio>
              </el-radio-group>
            </el-form-item>
          </div> -->
          <div>
            <el-form-item label="配送方式" prop="ship_way" style="width: 90%;">
              <el-checkbox-group v-model="baseInfoForm.ship_way">
                <el-checkbox v-if="showGlobal" :label="1">快递</el-checkbox>
                <el-checkbox v-if="showLocal" :label="2">同城配送</el-checkbox>
                <el-checkbox v-if="showLocal" :label="3">到店自提</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="baseInfoForm.ship_way.indexOf(1)>-1" label="快递运费" prop="freight_pricing_way" style="width: 90%;">
              <div class="flex mb15">
                <el-radio v-model="baseInfoForm.freight_pricing_way" :label="0">统一邮费</el-radio>
                <el-form-item prop="freight_unified_price" :maxlength="10">
                  <el-input style="width: 160px;" v-model="baseInfoForm.freight_unified_price">
                    <template slot="prepend">¥</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="flex">
                <el-radio v-model="baseInfoForm.freight_pricing_way" :label="1">运费模板</el-radio>
                <el-form-item prop="template_id">
                  <el-select
                    v-model="baseInfoForm.template_id"
                    placeholder="请选择快递运费模板"
                    clearable>
                    <el-option
                      v-for="item in tplList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item v-if="baseInfoForm.ship_way.indexOf(2)>-1" label="同城配送运费" prop="local_template_id">
              <el-select
                v-model="baseInfoForm.local_template_id"
                placeholder="请选择同城配送运费模板"
                clearable>
                <el-option
                  v-for="item in tplLocalList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <!--seo-->
        <div class="base-info-item">
          <h4>seo</h4>
          <div>
            <el-form-item label="seo标题">
              <el-input placeholder="最多60个字符" class="seo-text" @change="() => { baseInfoForm.page_title = baseInfoForm.page_title.trim() }" :maxlength="60"  v-model="baseInfoForm.page_title"></el-input>
            </el-form-item>
            <el-form-item label="seo关键字" >
              <el-input type="textarea" placeholder="最多200个字符" class="seo-text" rows="5" :maxlength="200" v-model="baseInfoForm.meta_keywords"></el-input>
            </el-form-item>
            <el-form-item label="seo描述">
              <el-input type="textarea" placeholder="最多200个字符" class="seo-text" rows="5" :maxlength="200" v-model="baseInfoForm.meta_description"></el-input>
            </el-form-item>
          </div>
        </div>
        <!--兑换许可 自营店显示-->
        <div class="base-info-item" v-if="parseInt(shopInfo.self_operated) === 1">
          <h4>兑换许可</h4>
          <div>
            <el-form-item label="积分兑换">
              <el-switch
                v-model="isShowExchangeConfig"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="开启"
                inactive-text="关闭"
                @change="handleSwitchexchange">
              </el-switch>
            </el-form-item>
          </div>
        </div>
        <!--积分配置-->
        <div class="base-info-item" v-if="isShowExchangeConfig">
          <h4>积分配置</h4>
          <div v-if="baseInfoForm.exchange">
            <el-form-item label="兑换条件" style="width: 25%;" prop="exchange_money">
              <el-input placeholder="最多10个字符" :maxlength="10" v-model="baseInfoForm.exchange.exchange_money" style="width: 100px;"></el-input> 元
            </el-form-item>
            <el-form-item  style="width: 25%;" prop="exchange_point">
              <el-input placeholder="最多10个字符" :maxlength="10" v-model.number="baseInfoForm.exchange.exchange_point" style="width: 100px;"></el-input> 积分
            </el-form-item>
            <el-form-item label="积分商品品类" >
              <el-select
                v-model="baseInfoForm.exchange.category_id"
                placeholder="请选择积分商品品类"
                @change="changeExangeCategory"
                clearable>
                <el-option
                  v-for="item in exchangeGoodsCatrgoryList"
                  :key="item.category_id"
                  :label="item.name"
                  :value="item.category_id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <!--商品参数-->
        <el-collapse :value="collapseVal">
          <el-collapse-item
            v-for="paramsgroup in  goodsParams"
            v-if="paramsgroup"
            :title="paramsgroup.group_name"
            :key="paramsgroup.group_id"
            :name="paramsgroup.group_id">
            <el-form-item
              v-for="(goods_params_list, index) in baseInfoForm.goods_params_list"
              v-if="goods_params_list && goods_params_list.group_id && paramsgroup.group_id === goods_params_list.group_id"
              :key="index"
              :label="`${goods_params_list.param_name}：`"
              :prop="'goods_params_list.' + index + '.param_value'"
              :rules="goods_params_list.required === 1 ? {required: true, message: `${goods_params_list.param_name}不能为空`, trigger: 'change' } : {}">
              <el-input
                placeholder="长度为最多100个字符"
                maxlength="100"
                v-if="goods_params_list.param_type === 1"
                v-model="goods_params_list.param_value" >
              </el-input>
              <el-select
                v-if="goods_params_list.param_type === 2"
                v-model="goods_params_list.param_value"
                placeholder="请选择"
                clearable>
                <el-option
                  v-for="(option) in goods_params_list.option_list"
                  :key="option"
                  :label="option"
                  :value="option">
                </el-option>
              </el-select>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
    <!--步骤2-->
    <div class="content-goods-publish" v-if="activestep === 1">
      <el-form
        :model="baseInfoForm"
        label-position="right"
        ref="baseInfoFormIntro"
        label-width="120px"
        class="demo-ruleForm">
        <el-form-item label="商品描述" class="goods-intro">
          <UE ref="ue" :defaultMsg="baseInfoForm.intro"></UE>
        </el-form-item>
      </el-form>
    </div>
    <!--底部-->
    <div class="footer">
      <el-button-group>
        <el-button type="primary" @click="pre" v-if="activestep === 1">上一步</el-button>
        <el-button
          type="primary"
          @click="next"
          v-if="activestep === 0">下一步</el-button>
        <el-button
          type="primary"
          @click="aboveGoods"
        >上架</el-button>
        <el-button
          type="primary"
          @click="handleUnderGoods"
          v-if="currentStatus === 1 && baseInfoForm.market_enable === 1"
        >下架</el-button>
        <el-button
          type="primary"
          @click="saveDraft"
          v-if="(currentStatus != 1)"
        >保存草稿</el-button>
      </el-button-group>
    </div>

    <!--选择商品品类弹层-->
    <el-dialog
      title="选择商品品类"
      width="800px"
      class="dialog-category"
      :visible.sync="dialogCategory"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="content-goods-publish">
        <div class="goods-category">
          <ul v-if="categoryListLevel1 && categoryListLevel1.length > 0">
            <li v-for="(item, index) in categoryListLevel1"
              :key="`level1-${index}`"
              :class="{'activeClass':index == dialogActiveCategoryIndex1}"
              @click="handleSelectCategory(item, index, 1)">
              <span>{{ item.name }}</span> <span>》</span>
            </li>
          </ul>
          <ul v-if="categoryListLevel2 && categoryListLevel2.length > 0">
            <li v-for="(item,index) in categoryListLevel2"
              :key="`level2-${index}`"
              :class="{'activeClass':index == dialogActiveCategoryIndex2}"
              @click="handleSelectCategory(item, index, 2)">
              <span>{{ item.name }}</span> <span>》</span>
            </li>
          </ul>
          <ul v-if="categoryListLevel3 && categoryListLevel3.length > 0">
            <li v-for="(item,index) in categoryListLevel3"
              :key="`level3-${index}`"
              :class="{'activeClass':index == dialogActiveCategoryIndex3}"
              @click="handleSelectCategory(item, index, 3)">
              <span>{{ item.name }}</span> <span>》</span>
            </li>
          </ul>
        </div>
        <p class="current-goods-category">
          已选品类：
          <span>{{ dialogActiveCategoryName1 }}</span>
          <span v-show="dialogActiveCategoryName2"> > {{ dialogActiveCategoryName2 }}</span>
          <span v-show="dialogActiveCategoryName3"> > {{ dialogActiveCategoryName3 }}</span>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogCategory = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitCategory()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Storage from '@/utils/storage'
  import dg_select from '@/components/dg-select'
  import { getDictData, filterShowDict } from '@/common/filter-show';
  import * as API_goods from '@/api/goods'
  import * as API_goodsCategory from '@/api/goodsCategory'
  import { CategoryPicker, SkuSelector, UE, UploadSortable } from '@/components'
  import { RegExp } from '~/ui-utils'
  import Sortable from 'sortablejs'
  const timerOptions = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
  export default {
    name: 'goodPublish',
    components: {
      [CategoryPicker.name]: CategoryPicker,
      [SkuSelector.name]: SkuSelector,
      [UploadSortable.name]: UploadSortable,
      [UE.name]: UE,
      'dg-select': dg_select
    },
    data() {
      const checkSn = (rule, value, callback) => {
        if (value && !/^[a-zA-Z0-9_\\-]+$/g.test(value)) {
          callback(new Error('请输入数字、字母、下划线或者中划线'))
        } else {
          callback()
        }
      }

      const checkMarket = (rule, value, callback) => {
        if (value) {
          if (!RegExp.money.test(value)) {
            callback(new Error('请输入正整数或者两位小数'))
          } else if (parseFloat(value) > 99999999) {
            callback(new Error('市场价格设置超过上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }

      const checkPrice = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error('商品价格不能为空'))
        }
        setTimeout(() => {
          if (!RegExp.money.test(value)) {
            callback(new Error('请输入正整数或者两位小数'))
          } else if (parseFloat(value) > 99999999) {
            callback(new Error('商品价格设置超过上限值'))
          } else {
            callback()
          }
        }, 1000)
      }

      const checkCost = (rule, value, callback) => {
        if (value && !RegExp.money.test(value)) {
          callback(new Error('请输入正整数或者两位小数'))
        } else if (value && parseFloat(value) > 99999999) {
          callback(new Error('成本价格设置超过上限值'))
        } else {
          callback()
        }
      }

      // const checkWeight = (rule, value, callback) => {
      //   if (this.baseInfoForm.goods_type === 0) {
      //     if (!value && typeof value !== 'number') {
      //       callback(new Error('重量不能为空'))
      //     } else if (!RegExp.money.test(value)) {
      //       callback(new Error('请输入正整数或者两三位小数'))
      //     } else if (parseFloat(value) > 99999999) {
      //       callback(new Error('商品重量设置超过上限值'))
      //     } else {
      //       callback()
      //     }
      //   } else {
      //     callback()
      //   }
      //   // if (value) {
      //   //   if (!RegExp.money.test(value)) {
      //   //     callback(new Error('请输入正整数或者两位小数'))
      //   //   } else if (parseFloat(value) > 99999999) {
      //   //     callback(new Error('商品重量设置超过上限值'))
      //   //   } else {
      //   //     callback()
      //   //   }
      //   // } else {
      //   //   callback()
      //   // }
      // }

      const checkUnifiedPrice = (rule, value, callback) => {
        if (this.baseInfoForm.freight_pricing_way === 0 && !value && value !== 0) {
          return callback(new Error('统一邮费不能为空'))
        }
        setTimeout(() => {
          if (value && !RegExp.money.test(value)) {
            callback(new Error('请输入正整数或者两位小数'))
          } else if (value && parseFloat(value) > 99999999) {
            callback(new Error('统一邮费设置超过上限值'))
          } else {
            callback()
          }
        }, 1000)
      }

      const checkTplId = (rule, value, callback) => {
        if (this.baseInfoForm.freight_pricing_way === 1 && !value) {
          return callback(new Error('请选择快递运费模板'))
        } else {
          callback()
        }
      }

      // 总库存
      const checkQuantity = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请填写总库存'))
        } else if (!RegExp.integer.test(value)) {
          callback(new Error('请输入大于0的正整数'))
        } else {
          if (parseInt(value) > 99999999) {
            callback(new Error('总库存不得大于99999999'))
          } else {
            callback()
          }
        }
      }

      const checkExchangePoint = (rule, value, callback) => {
        if (this.baseInfoForm.exchange.enable_exchange && !this.baseInfoForm.exchange.exchange_point) {
          return callback(new Error('积分值不能为空且不能为0'))
        }
        setTimeout(() => {
          if (!RegExp.integer.test(this.baseInfoForm.exchange.exchange_point)) {
            callback(new Error('请输入正整数'))
          } else {
            if (parseInt(this.baseInfoForm.exchange.exchange_point) <= 0) {
              callback(new Error('请输入大于0的积分值'))
            } else {
              callback()
            }
          }
        }, 1000)
      }

      const checkExchangeMoney = (rule, value, callback) => {
        if (this.baseInfoForm.exchange.exchange_money !== 0 && !this.baseInfoForm.exchange.exchange_money) {
          callback(new Error('积分所需金额不能为空'))
        } else if (!RegExp.money.test(this.baseInfoForm.exchange.exchange_money)) {
          callback(new Error('请输入正确的金额'))
        } else if (parseFloat(this.baseInfoForm.exchange.exchange_money) >= parseFloat(this.baseInfoForm.price)) {
          callback(new Error('积分商品价格不能高于商品原价'))
        } else {
          callback()
        }
      }

      return {
        percentage: '0',
        interval: '',
        /** 店铺信息 */
        shopInfo: this.$store.getters.shopInfo,

        /** 加载中。。。 */
        loading: false,

        /** 当前状态/模式 默认发布商品0 编辑商品1 编辑草稿箱商品2 */
        currentStatus: 0,

        /** 当前激活步骤*/
        activestep: 0,

        /** 当前商品品类名称1*/
        activeCategoryName1: '',

        /** 当前商品品类名称2*/
        activeCategoryName2: '',

        /** 当前商品品类名称3*/
        activeCategoryName3: '',

        /** 当前商品id*/
        activeGoodsId: '',

        /** 1级分类列表*/
        categoryListLevel1: [],

        /** 2级分类列表*/
        categoryListLevel2: [],

        /** 3级分类列表*/
        categoryListLevel3: [],

        showGlobal: false, // 显示’快递‘

        showLocal: false, // 显示’同城配送‘、'店铺自提'

        //可选日期参数
        weekTime: timerOptions,
        //可选日期全选
        checkAll: false,
        isIndeterminate: false,

        /** 商品详情信息提交表单 */
        baseInfoForm: {
          /** 商品类型 */
          goods_type: 0,
          /** 过期时间 */
          expiry_day: null,

          /** 商品名称 */
          goods_name: '',

          /** 商品卖点 */
          selling: '',

          /** 用来校验的商品相册 */
          goods_gallery: '',

          /** 商品相册列表 */
          goods_gallery_list: [],

          /** 主图视频 */
          video_url: '',

          /** 商品品类id */
          category_id: null,

          /** 商品品类 名称 */
          category_name: '',

          /** 商品分组id*/
          shop_cat_id: 0,

          /** 商品品牌id */
          brand_id: '',

          /** 商品价格 */
          price: '',

          /** 市场价格 */
          mktprice: '',

          /** 商品总库存 */
          quantity: null,

          /** 商品重量 */
          weight: '',

          /** 商品编码 sn*/
          sn: '',

          /** 成本价格 */
          cost: '',

          /** 卖家承担运费1 买家承担运费0 */
          goods_transfee_charge: 1,

          /** sku数据变化或者组合变化判断 0:没变化，1：变化 */
          has_changed: 0,

          /** 是否上架，1上架 0下架 */
          market_enable: 1,

          /** 用来校验的 配送方式 */
          ship_way: [],

          /** 快递运费 */
          freight_pricing_way: 0,

          /** 统一邮费 */
          freight_unified_price: '',

          /** 模板快递运费id */
          template_id: undefined,

          /** 模板同城配送运费id */
          local_template_id: undefined,

          is_local: false,

          is_global: false,

          is_self_take: false,

          /** 积分兑换 */
          exchange: {
            /** 积分兑换所属分类 */
            category_id: '',

            /** 是否允许积分兑换  1是 0否*/
            enable_exchange: 1,

            /** 兑换所需金额 */
            exchange_money: 0,

            /** 积分兑换使用的积分 */
            exchange_point: 0
          },

          /** seo描述 */
          meta_description: '',

          /** seo关键字 */
          meta_keywords: '',

          /** seo标题 */
          page_title: '',

          /** 商品参数列表 */
          goods_params_list: [],

          /** sku列表 */
          sku_list: [],

          /** 商品描述 详情 */
          intro: '',

          /** 供应商 */
          supplier_name: '',

          /** 外部商品ID */
          up_goods_id: '',

          /** 贮存方式 */
          store: undefined,

          /** 截止日期 */
          expiryDay: undefined,

          /** 可用日期 */
          available_date: [],

          /** 分拣类型 */
          pre_sort: 0

        },

        /** 临时存储商品相册信息 */
        goodsGalleryList: [],

        /** 用来向组件中传递的数据 */
        skuList: [],

        /** 是否自动生成货号 */
        productSn: false,

        /** 总库存是否可编辑 默认可以 false可编辑 true不可编辑 */
        isEditQuantity: false,

        /** 请求的商品参数组列表 */
        goodsParams: [
          {
            group_id: '',
            group_name: '',
            params: [
              {
                param_id: 0,
                param_name: '',
                param_type: 1,
                param_value: '',
                required: 0,
                option_list: [
                  { value: 1, label: '' },
                  { value: 2, label: '' }
                ]
              }
            ]
          }
        ],

        /** */
        collapseVal: [],

        /** 品牌列表 */
        brandList: [],

        /** 快递运费模板列表 */
        tplList: [],

        /** 同城配送运费模板列表 */
        tplLocalList: [],

        /** 积分商品列表 */
        exchangeGoodsCatrgoryList: [],

        /** 商品图片放大地址 */
        dialogImageUrl: '',

        /** 是否显示放大图片弹框 */
        dialogImage: false,

        /** 是否显示积分配置*/
        isShowExchangeConfig: false,

        /** 商品详情的校验规则 */
        baseInfoFormRule: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { whitespace: true, message: '商品名称不可为纯空格', trigger: 'blur' },
            { min: 3, max: 60, message: '长度在 3 到 60 个字符', trigger: 'blur' }
          ],
          category_id: [
            { required: true, message: '请选择商品品类', trigger: 'change' }
          ],
          expiry_day: [
            { required: true, message: '请选择过期时间', trigger: 'change' }
          ],
          available_date: [
            { required: true, message: '请选择可用日期', trigger: 'change' }
          ],
          sn: [
            { validator: checkSn, trigger: 'blur' }
          ],
          mktprice: [
            { required: true, message: '请输入市场价格', trigger: 'blur' },
            { validator: checkMarket, trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            { validator: checkPrice, trigger: 'blur' }
          ],
          cost: [
            { required: true, message: '请输入成本价格', trigger: 'blur' },
            { validator: checkCost, trigger: 'blur' }
          ],
          // weight: [
          //   { validator: checkWeight, trigger: 'blur' }
          // ],
          goods_gallery: [
            { required: true, validator: (rule, value, callback) => {
              if (!this.baseInfoForm.goods_gallery) {
                return callback(new Error('请上传商品图片'))
              } else {
                callback()
              }
            }, trigger: 'change' }
          ],
          quantity: [
            { required: true, message: '请填写总库存', trigger: 'blur' },
            { validator: checkQuantity, trigger: 'blur' }
          ],
          ship_way: [
            { required: true, message: '请选择配送方式', trigger: 'change' }
          ],
          freight_unified_price: [
            { validator: checkUnifiedPrice, trigger: 'blur' }
          ],
          template_id: [
            { validator: checkTplId, trigger: 'change' }
          ],
          local_template_id: [
            { required: true, message: '请选择同城配送运费模板', trigger: 'change' }
          ],
          exchange_money: [
            { validator: checkExchangeMoney, trigger: 'blur' }
          ],
          exchange_point: [
            { validator: checkExchangePoint, trigger: 'blur' }
          ]
          // store: [
          //   {
          //     required: true,
          //     message: '贮存方式不能为空',
          //     trigger: 'change'
          //   }
          // ],
          // pre_sort: [
          //   {
          //     required: true,
          //     message: '分拣类型不能为空',
          //     trigger: 'blur'
          //   }
          // ]
        },

        /** 选择商品品类弹层 */
        dialogCategory: false,

        /** 当前点击的1级分类索引*/
        dialogActiveCategoryIndex1: -1,
        /** 当前点击的2级分类索引*/
        dialogActiveCategoryIndex2: -1,
        /** 当前点击的3级分类索引*/
        dialogActiveCategoryIndex3: -1,
        /** 弹层商品品类名称1*/
        dialogActiveCategoryName1: '',
        /** 弹层商品品类名称2*/
        dialogActiveCategoryName2: '',
        /** 弹层商品品类名称3*/
        dialogActiveCategoryName3: '',
        /** 弹层商品品类id*/
        dialogCategory_id: null,

        video_ico: false
      }
    },
    filters: {
      // 字典显示转换
      filterDict (_stateVal, _dictType) {
        return filterShowDict(_dictType, _stateVal);
      }
    },
    mounted() {
      /** 获取该商城分类下 商品参数信息 */
      /** 运费模板列表 */
      this.getTplList()
      /** 积分商品品类列表 */
      this.getGoodsCatrgory()
      /** 配送类型 */
      this.getShipShow()
      if (this.$route.params && this.$route.params.goodsid) {
        this.currentStatus = parseInt(this.$route.params.isdraft) || 0
        this.activeGoodsId = this.$route.params.goodsid
        this.activestep = 0
        if (this.currentStatus === 1 && this.$route.params.goodsid) {
          this.GET_GoodData()
        } else if (this.currentStatus === 2 && this.$route.params.goodsid) {
          this.GET_GoodDraftData()
        }
      }
      // 获取格式化字典数据
      getDictData('goods_tag_color');
    },
    activated() {
      /** 获取该商城分类下 商品参数信息 */
      /** 查询品牌列表 */
      // this.getGoodsBrandList()
      /** 运费模板列表 */
      this.getTplList()
      /** 积分商品品类列表 */
      this.getGoodsCatrgory()
      /** 配送类型 */
      this.getShipShow()
      if (this.$route.params && this.$route.params.goodsid) {
        this.currentStatus = parseInt(this.$route.params.isdraft) || 0
        this.activeGoodsId = this.$route.params.goodsid
        this.activestep = 0
        if (this.currentStatus === 1 && this.$route.params.goodsid) {
          this.GET_GoodData()
        } else if (this.currentStatus === 2 && this.$route.params.goodsid) {
          this.GET_GoodDraftData()
        }
      }
    },
    methods: {
      //可用日期全选
      handleCheckAllChange(val) {
        this.baseInfoForm.available_date = val ? timerOptions : [];
        this.isIndeterminate = false;
      },
      //
      handleCheckedWeekTimeChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.weekTime.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.weekTime.length;
        console.log('value:', value)
      },
      onProgress(event, file, fileList) {
        this.video_ico = true;
        this.interval = setInterval(() => {
          if (this.percentage < 100) {
            this.percentage = Math.round(event.percent);
          } else {
            clearInterval(this.interval);
            this.video_ico = false;
          }
        }, 3000);
      },
      /*
        * @date 2020-03-10
        * @author wolfMan
        * @description {视屏校验}
      */
      beforeUploadVideo(file) {
        let fileSize = file.size / 1024 / 1024 < 50
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) === -1) {
          this.$message.error('请上传正确的视频格式')
          return false
        }
        if (!fileSize) {
          this.$message.error('视频大小不能超过50MB')
          return false
        }
      },
      /*
        * @date 2020-03-04
        * @author wolfMan
        * @description {视屏上传成功}
      */
      uploadVideo(res) {
        this.baseInfoForm.video_url = res.url
        this.$forceUpdate()
      },
      /*
        * @date 2020-03-04
        * @author wolfMan
        * @description {视屏移除}
      */
      removeVideo() {
        this.baseInfoForm.video_url = ''
        this.$forceUpdate()
      },
      /*
        * @date 2020-03-10
        * @author wolfMan
        * @description {选择商品品类}
      */
      async showCategory() {
        await this.GET_NextLevelCategory()
        const _hasCategory = this.dialogCategory_id
        this.dialogActiveCategoryName1 = _hasCategory ? this.dialogActiveCategoryName1 : ''
        this.dialogActiveCategoryName2 = _hasCategory ? this.dialogActiveCategoryName2 : ''
        this.dialogActiveCategoryName3 = _hasCategory ? this.dialogActiveCategoryName3 : ''
        this.dialogCategory = true
      },
      /** 选择商城商品品类 */
      handleSelectCategory(row, index, level) {
        if (level === 1) {
          this.dialogActiveCategoryName1 = row.name
          this.dialogActiveCategoryName2 = this.dialogActiveCategoryName3 = ''
          this.dialogActiveCategoryIndex1 = index
          this.dialogActiveCategoryIndex2 = -1
          this.dialogActiveCategoryIndex3 = -1
        } else if (level === 2) {
          this.dialogActiveCategoryName2 = row.name
          this.dialogActiveCategoryName3 = ''
          this.dialogActiveCategoryIndex2 = index
          this.dialogActiveCategoryIndex3 = -1
        } else {
          this.dialogActiveCategoryName3 = row.name
          this.dialogActiveCategoryIndex3 = index
        }
        // 设置当前商城分类ID
        this.dialogCategory_id = row.category_id
        this.GET_NextLevelCategory(row, level)
      },
      /** 查询下一级 商城商品品类*/
      GET_NextLevelCategory(row, level, not_click = false) {
        this.loading = true
        const _id = row && row.category_id !== 0 ? row.category_id : 0
        API_goodsCategory.getGoodsCategoryLevelList(_id, { }).then((response) => {
          this.loading = false
          if (level === 1) {
            this.categoryListLevel2 = response
            this.categoryListLevel3 = []
            if (this.baseInfoForm.category_ids && this.baseInfoForm.category_ids[1] && not_click) {
              const _res = response.map(key => key.category_id)
              const row = response.filter(key => key.category_id === this.baseInfoForm.category_ids[1])[0]
              this.dialogActiveCategoryName2 = row.name
              this.dialogActiveCategoryIndex2 = _res.indexOf(this.baseInfoForm.category_ids[1])
              this.GET_NextLevelCategory(row, 2, true)
            }
          } else if (level === 2) {
            this.categoryListLevel3 = response
            if (this.baseInfoForm.category_ids && this.baseInfoForm.category_ids[2] && not_click) {
              const _res = response.map(key => key.category_id)
              const row = response.filter(key => key.category_id === this.baseInfoForm.category_ids[2])[0]
              this.dialogActiveCategoryName3 = row.name
              this.dialogActiveCategoryIndex3 = _res.indexOf(this.baseInfoForm.category_ids[2])
            }
          } else if (!level) {
            this.categoryListLevel1 = response
            if (this.baseInfoForm.category_ids && this.baseInfoForm.category_ids[0] && not_click) {
              const _res = response.map(key => key.category_id)
              const row = response.filter(key => key.category_id === this.baseInfoForm.category_ids[0])[0]
              this.dialogActiveCategoryName1 = row.name
              this.dialogActiveCategoryIndex1 = _res.indexOf(this.baseInfoForm.category_ids[0])
              this.GET_NextLevelCategory(row, 1, true)
            }
          }
        })
      },
      /*
        * @date 2020-03-10
        * @author wolfMan
        * @description {商品品类提交}
      */
      submitCategory() {
        if (!this.dialogActiveCategoryName3) {
          this.$message.error('请选择完整的三级商品品类')
        } else {
          this.activeCategoryName1 = this.dialogActiveCategoryName1
          this.activeCategoryName2 = this.dialogActiveCategoryName2
          this.activeCategoryName3 = this.dialogActiveCategoryName3
          this.baseInfoForm.category_id = this.dialogCategory_id
          /** 查询品牌列表 */
          this.getGoodsBrandList()
          /** 传参数1 表示查询添加模式（发布商品模式0）下的商品参数信息；  如果不传 表示查询编辑（包括草稿箱编辑）模式下的商品参数信息 */
          this.GET_GoodsParams(1)
          this.dialogCategory = false
        }
      },
      /** 获取店铺配送类型*/
      getShipShow() {
        const _shipType = JSON.parse(Storage.getItem('seller_shop')).ship_type
        this.showGlobal = _shipType && _shipType.indexOf('1') > -1
        this.showLocal = _shipType && _shipType.indexOf('2') > -1
      },
      /** 上一步*/
      pre() {
        this.activestep--
      },

      /** 下一步*/
      next() {
        this.loading = true
        this.$refs['baseInfoForm'].validate((valid) => {
          if (valid) {
            /** 规格校验 */
            if (!this.skuFormVali()) {
              this.loading = false
              return
            }
            this.loading = false
            if (this.activestep++ > 1) return
          } else {
            this.loading = false
            this.$message.error('表单中存在未填写或者填写有误的地方,已有错误标示，请检查并正确填写')
          }
        })
        return
      },

      /** 保存草稿 */
      saveDraft() {
        const _params = this.generateFormData(this.baseInfoForm)
        if (this.activeGoodsId) {
          this.activeGoodsId = this.activeGoodsId || 1
          /** 修改草稿箱商品 */
          API_goods.editDraftGoods(this.activeGoodsId, _params).then(() => {
            this.$message.success('修改草稿箱商品成功')
            this.$store.dispatch('delCurrentViews', {
              view: this.$route,
              $router: this.$router
            })
            this.$router.push({ path: '/goods/draft-list' })
            this.$route.params.callback()
          })
        } else {
          /** 保存草稿操作 */
          API_goods.saveDraft(_params).then(() => {
            this.$message.success('保存草稿成功')
            this.$route.params.callback()
            this.$store.dispatch('delCurrentViews', {
              view: this.$route,
              $router: this.$router
            })
            this.$router.push({ path: '/goods/draft-list' })
          })
        }
        /** 规格校验 */
        // if (!this.skuFormVali(true)) {
        //   return
        // }
        // this.$refs['baseInfoForm'].validate((valid) => {
        //   if (valid) {
        //     if (this.activeGoodsId) {
        //       this.activeGoodsId = this.activeGoodsId || 1
        //       /** 修改草稿箱商品 */
        //       API_goods.editDraftGoods(this.activeGoodsId, _params).then(() => {
        //         this.$message.success('修改草稿箱商品成功')
        //         this.$router.push({ path: '/goods/draft-list' })
        //         this.$route.params.callback()
        //       })
        //     } else {
        //       /** 保存草稿操作 */
        //       API_goods.saveDraft(_params).then(() => {
        //         this.$message.success('保存草稿成功')
        //         this.$route.params.callback()
        //         this.$router.push({ path: '/goods/draft-list' })
        //       })
        //     }
        //   } else {
        //     this.$message.error('表单中存在未填写或者填写有误的地方,已有错误标示，请检查并正确填写')
        //   }
        // })
      },

      /** 上架  */
      async aboveGoods() {
        if (this.baseInfoForm.activeGoodsId === 0) {
          this.$message.error('严重错误，商城分类Id不可为0')
          return
        }
        /** 规格校验 */
        if (!this.skuFormVali()) return
        let _params = this.generateFormData(this.baseInfoForm)
        /** 是否规格维度发生变化 */
        const final = this.baseInfoForm.sku_list.map(key => { if (key && key.sku_id) return key.sku_id })
        const _final = this.skuList.map(key => { if (key && key.sku_id) return key.sku_id })
        const _result = _final.every(key => final.includes(key))
        if (final.length && _final.length && this.currentStatus === 1 && !_result) {
          await this.$confirm('因规格的维度发生变化，会导致之前的SKU组合不存在，这会使相应的SKU参加的促销失效，确认要这么操作吗？', '提示', { type: 'warning' })
        }
        /** 如果规格无变化 则传0 有变化传1 */
        if (!_params.has_changed) _params.has_changed = 0
        /** 上架 market_enable 1上架0下架*/
        _params.market_enable = 1
        this.$refs['baseInfoForm'].validate((valid) => {
          if (valid) {
            _params.is_global = _params.is_global ? 1 : 0
            _params.is_local = _params.is_local ? 1 : 0
            _params.is_self_take = _params.is_self_take ? 1 : 0
            if (this.currentStatus !== 2) {
              if (this.activeGoodsId) {
                let ship_wayVal = this.baseInfoForm.ship_way
                if (ship_wayVal.indexOf(1) === -1) {
                  _params.freight_pricing_way = 1
                  _params.freight_unified_price = 0
                  _params.template_id = 0
                } 
                if (ship_wayVal.indexOf(2) === -1) {
                  delete _params.local_template_id
                }
                /** 修改正常商品 */
                API_goods.editGoods(this.activeGoodsId, _params).then(() => {
                  this.$message.success('修改商品成功')
                  this.$store.dispatch('delCurrentViews', {
                    view: this.$route,
                    $router: this.$router
                  })
                  this.$router.push({ path: '/goods/goods-list' })
                })
              } else {
                for (let i = 0; i < this.baseInfoForm.goods_gallery_list.length; i++) {
                  this.baseInfoForm.goods_gallery_list[i].sort = i
                }
                /** 正常商品上架 */
                API_goods.aboveGoods(_params).then(() => {
                  this.$message.success('上架商品成功')
                  this.$store.dispatch('delCurrentViews', {
                    view: this.$route,
                    $router: this.$router
                  })
                  this.$router.push({ path: '/goods/goods-list' })
                })
              }
            } else {
              API_goods.aboveDraftGoods(this.activeGoodsId, _params).then(() => {
                this.$message.success('上架草稿箱商品成功')
                this.$store.dispatch('delCurrentViews', {
                  view: this.$route,
                  $router: this.$router
                })
                this.$router.push({ path: '/goods/goods-list' })
              })
            }
          } else {
            this.$message.error('表单中存在未填写或者填写有误的地方,已有错误标示，请检查并正确填写')
          }
        })
      },

      /** 下架*/
      handleUnderGoods() {
        API_goods.underGoods(this.activeGoodsId, { }).then(() => {
          this.$message.success('下架成功')
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ path: '/goods/goods-list' })
        })
      },

      /** 查询单个商品信息*/
      GET_GoodData() {
        API_goods.getGoodData(this.activeGoodsId, {}).then((response) => {
          response.ship_way = []
          if (response.is_global === 1) {
            response.ship_way.push(1)
          }
          if (response.is_local === 1) {
            response.ship_way.push(2)
          }
          if (response.is_self_take === 1) {
            response.ship_way.push(3)
          }
          response.goods_type = response.is_global || response.is_local || response.is_self_take ? 0 : 1
          this.baseInfoForm = {
            ...response
          }
          /** 此处完成商品信息赋值 进行判断如果有值的话 */
          if (response.available_date && response.available_date!=='false') {
            let availableDate = response.available_date.split(',')
            availableDate = availableDate.map( item => item.replace(item, '周'+item))
            this.baseInfoForm.available_date = availableDate
          }
          /** 商品相册校验属性 */
          this.baseInfoForm.goods_gallery_list.forEach(key => {
            this.$set(key, 'url', key.original)
          })
          this.baseInfoForm.goods_gallery = this.baseInfoForm.goods_gallery_list.toString()
          this.goodsGalleryList = JSON.parse(JSON.stringify(this.baseInfoForm.goods_gallery_list))
          /** 商品规格校验属性  */
          if (!this.baseInfoForm.sku_list || !Array.isArray(this.baseInfoForm.sku_list)) {
            this.baseInfoForm.sku_list = []
          }
          /** 积分相关设置 如果没有积分相关则设置为空 */
          if (!this.baseInfoForm.exchange || !this.baseInfoForm.exchange.enable_exchange) {
            this.baseInfoForm.exchange = {
              /** 积分兑换所属分类 */
              category_id: '',
              /** 是否允许积分兑换  1是 0否*/
              enable_exchange: 0,
              /** 兑换所需金额 */
              exchange_money: 0,
              /** 积分兑换使用的积分 */
              exchange_point: 0
            }
          } else {
            this.isShowExchangeConfig = (this.baseInfoForm.exchange.enable_exchange === 1)
          }
          /** 查询品牌列表 */
          this.getGoodsBrandList()

          /** 查询商品参数 */
          this.GET_GoodsParams()

          /** 查询商品sku信息 */
          API_goods.getGoodsStockList(this.activeGoodsId, {}).then((response) => {
            /** 构造临时规格数据 */
            this.skuList = response.map(key => {
              if (key && key.spec_list && Array.isArray(key.spec_list)) {
                const spec_list = key.spec_list.map(item => {
                  let { spec_id, spec_image, spec_type, spec_value, spec_value_id, spec_name } = item
                  return { spec_id, spec_image, spec_type, spec_value, spec_value_id, spec_name }
                })
                let _spec_value_id = key.spec_list.map(item => item.spec_value_id).join('|')
                let { cost, quantity, sn, weight, sku_id, up_sku_id } = key
                const price = key.price
                return { cost, price, quantity, sn, weight, sku_id, up_sku_id, spec_list, _spec_value_id }
              }
            })
          })
        })
      },

      /** 查询商品参数 */
      GET_GoodsParams(next = null) {
        if (this.activeGoodsId && !next) {
          API_goods.getEditGoodsParams(this.baseInfoForm.category_id, this.activeGoodsId).then((response) => {
            this.loading = false
            this.goodsParams = response
            this.collapseVal = this.goodsParams.map(key => {
              if (key.group_id) {
                return key.group_id
              }
            })
            if (!response || response.length <= 0) {
              return
            }
            this.baseInfoForm.goods_params_list = []
            this.goodsParams.forEach(key => {
              if (key && key.params) {
                key.params.forEach(elem => {
                  this.baseInfoForm.goods_params_list.push(elem)
                })
              }
            })
          })
        } else {
          API_goods.getGoodsParams(this.baseInfoForm.category_id).then((response) => {
            this.loading = false
            this.goodsParams = response
            this.collapseVal = this.goodsParams.map(key => {
              if (key.group_id) {
                return key.group_id
              }
            })
            if (!response || response.length <= 0) {
              return
            }
            this.baseInfoForm.goods_params_list = []
            this.goodsParams.forEach(key => {
              if (key && key.params) {
                key.params.forEach(elem => {
                  this.baseInfoForm.goods_params_list.push(elem)
                })
              }
            })
          })
        }
      },

      /** 查询单个草稿箱商品信息 */
      GET_GoodDraftData() {
        API_goods.getGoodDraftData(this.activeGoodsId, {}).then((response) => {
          /** 此处完成商品信息赋值 进行判断如果有值的话 */
          response.ship_way = []
          if (response.is_global === 1) {
            response.ship_way.push(1)
          }
          if (response.is_local === 1) {
            response.ship_way.push(2)
          }
          if (response.is_self_take === 1) {
            response.ship_way.push(3)
          }
          response.goods_type = response.is_global || response.is_local || response.is_self_take ? 0 : 1
          this.baseInfoForm = { ...response }
          /** 积分相关设置 如果没有积分相关则设置为空 */
          if (this.baseInfoForm.exchange_category_id || this.baseInfoForm.goods_type === 'POINT') {
            this.$set(this.baseInfoForm, 'exchange', {
              category_id: response.exchange_category_id,

              enable_exchange: response.goods_type === 'POINT' ? 1 : 0,

              exchange_money: response.exchange_money,

              exchange_point: response.exchange_point
            })
            this.isShowExchangeConfig = (this.baseInfoForm.exchange.enable_exchange === 1)
          }
          /** 查询品牌列表 */
          this.getGoodsBrandList()

          /** 商品相册校验属性 */
          if (Array.isArray(response.gallery_list) && response.gallery_list.length) {
            this.baseInfoForm.goods_gallery_list = response.gallery_list.map(key => {
              return {
                img_id: -1,
                url: key,
                original: key,
                sort: 0
              }
            })
            this.baseInfoForm.goods_gallery = this.baseInfoForm.goods_gallery_list.toString()
          }
          if (!this.baseInfoForm.goods_gallery_list) this.baseInfoForm.goods_gallery_list = []
          this.goodsGalleryList = JSON.parse(JSON.stringify(this.baseInfoForm.goods_gallery_list))
          /** 商品规格校验属性  */
          if (!this.baseInfoForm.sku_list) {
            this.baseInfoForm.sku_list = []
          }

          /** 查询草稿箱商品参数信息 */
          this.GET_GoodsDtagtParams()

          /** 查询草稿箱sku信息 */
          API_goods.draftSku(this.activeGoodsId, {}).then((response) => {
            /** 构造临时规格数据 */
            this.skuList = response.map(key => {
              if (key && key.spec_list && Array.isArray(key.spec_list)) {
                const spec_list = key.spec_list.map(item => {
                  let { spec_id, spec_image, spec_type, spec_value, spec_value_id, spec_name } = item
                  return { spec_id, spec_image, spec_type, spec_value, spec_value_id, spec_name }
                })
                let { cost, quantity, sn, weight, up_sku_id } = key
                const price = key.price
                return { cost, price, quantity, sn, weight, up_sku_id, spec_list }
              }
            })
          })
        })
      },

      /** 查询草稿箱商品参数信息 */
      GET_GoodsDtagtParams() {
        // 处理数据 方便校验
        const goods_id = this.activeGoodsId || 1
        API_goods.getGoodsDraftParams(goods_id).then((response) => {
          this.loading = false
          if (!response || response.length <= 0) {
            return
          }
          this.goodsParams = response
          this.collapseVal = this.goodsParams.map(key => {
            if (key.group_id) {
              return key.group_id
            }
          })
          this.baseInfoForm.goods_params_list = []
          this.goodsParams.forEach(key => {
            if (key && key.params) {
              key.params.forEach(elem => {
                this.baseInfoForm.goods_params_list.push(elem)
              })
            }
          })
        })
      },

      /** 商品分组组件 改变时触发 */
      changeGoodsCateGory(val) {
        this.baseInfoForm.shop_cat_id = val[val.length - 1]
      },

      /** 查询商品品牌列表 */
      getGoodsBrandList() {
        API_goods.getGoodsBrandList(this.baseInfoForm.category_id, { }).then((response) => {
          this.brandList = response
        })
      },

      /** 商品品牌 改变时触发 */
      changeGoodsBrand(val) {
        this.baseInfoForm.brand_id = val
      },

      /** 运费模板列表 */
      getTplList() {
        API_goods.getTplList(this.activeGoodsId, { }).then((response) => {
          let _tpl = []
          let _tplLocal = []
          response.forEach(item => {
            if (item.template_type === 'KUAIDI') {
              _tpl.push(item)
            } else {
              _tplLocal.push(item)
            }
          })
          this.tplList = _tpl
          this.tplLocalList = _tplLocal
        })
      },

      /** 选中值卖家运费/买家运费时触发 */
      changeTplItem(val) {
        if (this.tplList[0] && this.tplList[0].id) {
          this.baseInfoForm.template_id = val === 0 ? this.tplList[0].id : ''
        }
      },

      /** 运费模板改变时触发 */
      // changeTpl(val) {
      //   this.baseInfoForm.template_id = this.baseInfoForm.goods_transfee_charge === 0 ? val : ''
      // },

      /** 积分商品商城分类列表 */
      getGoodsCatrgory() {
        API_goods.getExchangeCatsList(0).then((response) => {
          this.exchangeGoodsCatrgoryList = response
        })
      },

      /** 积分兑换开关值改变时触发 */
      handleSwitchexchange(val) {
        this.isShowExchangeConfig = val
        if (val) {
          this.baseInfoForm.exchange.enable_exchange = 1
        } else {
          this.baseInfoForm.exchange.enable_exchange = 0
        }
      },

      /** 积分商品商城分类 改变时触发*/
      changeExangeCategory(val) {
        this.baseInfoForm.exchange.category_id = val
      },

      /** 商品图片 改变时触发*/
      handlePictureClick() {
        console.log(123)
      },

      handlePictureChange(fileList) {
        this.goodsGalleryList = fileList
        this.baseInfoForm.goods_gallery = fileList
        this.baseInfoForm.goods_gallery_list = fileList
      },

      /** 规格选择器规格数据改变时触发 */
      finalSku(val) {
        // 如果没有规格 则不得编辑总库存
        this.isEditQuantity = !!val.length
        // 动态修改总库存 每次设置为0  此处每次进行循环计算 存在性能浪费
        // 如果是编辑模式 总库存不得重置为0
        this.baseInfoForm.quantity = 0
        val.forEach(key => {
          if (key.quantity) {
            this.baseInfoForm.quantity += parseInt(key.quantity)
          }
        })
        /** 删除 因为对象浅拷贝造成的字段冗余（不必要的字段）*/
        val.forEach(key => {
          key.spec_list.forEach(item => {
            delete item.cost
            delete item.price
            delete item.quantity
            delete item.sn
            delete item.weight
            delete item.up_sku_id
          })
        })
        this.baseInfoForm.sku_list = val
        /** 规格数据是否存在变化 */
        this.baseInfoForm.has_changed = 1
      },

      /** 构造表单数据 */
      generateFormData(data) {
        let _params = {
          ...data
        }
        if (_params.goods_type === 0) {
          const _shipWay = _params.ship_way
          _params.is_global = _shipWay.indexOf(1) > -1
          _params.is_local = _shipWay.indexOf(2) > -1
          _params.is_self_take = _shipWay.indexOf(3) > -1
        }
        // _params.goods_type = _params.goods_type === 0 ? 'NORMAL' : 'VIRTUAL';
        if (!!_params.available_date && _params.available_date!=='false' && _params.available_date!=='' && _params.available_date.length !==0) {
          _params.available_date = _params.available_date.map((item) => {
            return item.replace('周', '')
          })

          // let str = _params.available_date;
          // let arrTOstr = _params.available_date;
          _params.available_date = _params.available_date.join('、')
          // console.log('str:', str.join('、'))
          // console.log('arrTOstr:', arrTOstr.toString().replaceAll(',', '、'))
        } else {
          delete _params.available_date
        }
        // 删除不必要的表单数据
        _params.goods_type = _params.goods_type === 0 ? 'NORMAL' : 'VIRTUAL'
        // delete _params.goods_type
        delete _params.ship_way
        delete _params.original
        delete _params.exchange_category_id
        delete _params.exchange_money
        delete _params.exchange_point
        delete _params.gallery_list
        delete _params.goods_gallery
        if (_params.goods_gallery_list) {
          _params.goods_gallery_list.forEach(key => {
            delete key.name
            delete key.big
            delete key.goods_id
            delete key.isdefault
            delete key.small
            delete key.status
            delete key.thumbnail
            delete key.tiny
            delete key.uid
            delete key.url
          })
        }
        /** 积分商品数据 */
        if (!this.isShowExchangeConfig) {
          _params.exchange.enable_exchange = 0
        } else {
          _params.exchange.exchange_money = parseFloat(_params.exchange.exchange_money)
        }
        /** 运费模板 */
        _params.template_id = _params.template_id || 0
        /** 处理UE的信息 */
        if (this.activestep === 1) {
          _params.intro = this.$refs['ue'].getUEContent()
        }
        return _params
      },

      /** 商品规格选择器校验 */
      skuFormVali(isDraft) {
        /** 如果并未选择规格 */
        if (Array.isArray(this.baseInfoForm.sku_list) && this.baseInfoForm.sku_list.length === 0) {
          return true
        }
        this.productSn = false
        /** 是否自动生成货号校验 检测是否所有的货号都存在*/
        const _sn = this.baseInfoForm.sku_list.some(key => {
          return key.sn === ''
        })
        if (_sn) {
          this.$confirm('您没有为SKU填写货号，系统将根据商品货号自动生成, 是否继续?', '提示').then(() => {
            this.productSn = true
          })
          return false
        }
        /** 规格值空校验 */
        let _result = false;
        let skuList = JSON.parse(JSON.stringify(this.baseInfoForm.sku_list));
        skuList.forEach(key => {
          delete key.up_sku_id;
          Object.values(key).forEach(item => {
            if (!item && item !== 0) {
              _result = true
            }
          })
        })
        if (_result) {
          this.$message.error('存在未填写的规格值')
          return false
        }
        // 规格值校验
        let spec_fun = false
        let spec_tip
        this.baseInfoForm.sku_list.forEach(key => {
          if (!RegExp.money.test(key.cost)) {
            spec_fun = true
            spec_tip = '请输入正确的成本价金额'
          }
          if (!RegExp.money.test(key.price)) {
            spec_fun = true
            spec_tip = '请输入正确的价格'
          }
          if (!(parseInt(key.weight) >= 0 && parseInt(key.weight) < 99999999)) {
            spec_fun = true
            spec_tip = '重量须为0 - 99999999之间的整数'
          }
          if (!(parseInt(key.quantity) >= 0 && parseInt(key.quantity) < 99999999) || !/^[0-9]\d*$/.test(key.quantity)) {
            spec_fun = true
            spec_tip = '库存须为0 - 99999999之间的整数'
          }
        })
        if (spec_fun) {
          this.$message.error(spec_tip)
          return false
        }
        if (isDraft) {
          this.productSn = true
          return true
        }
        return true
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  .flex {
    display: flex;
  }
  .mb15 {
    margin-bottom: 15px !important;
  }
  .check_item {
    width: 150px!important;
    min-width: 150px!important;
  }
  .el-form-item__content {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  /*选择商品品类*/
  .publish-box {
    padding: 20px;
    margin: 0 auto;
    text-align: center;
    // border: 1px solid #ddd;
    background: none repeat  0 0 #fff;

    .el-radio {
      line-height: 32px;
    }
    /deep/ .el-steps--simple {
      padding: 14px 20%;
      border-radius: 0;
      .el-step__icon {
        display: none;
      }
      .el-step__title {
        color: #333;
        font-size: 14px;
        &.is-process {
          color: #3870EA;
          font-weight: 400;
        }
      }
    }

    /deep/ .pro-type-row {
      padding-top: 10px;
      margin-left: 0;
      text-align: left;
      .box-radio {
        .el-radio {
          padding: 10px;
          margin-right: 0;
          width: 140px;
          height: 60px;
          line-height: 20px;
          text-align: center;
          border-radius: 2px;
          box-sizing: border-box;
          color: #333;
          font-weight: 400;
          & + .el-radio {
            margin-left: 20px;
          }
          .el-radio__input {
            position: absolute;
            opacity: 0;
          }
          .el-radio__label {
            display: block;
            padding: 0;
            font-size: 14px;
          }
          .radio-tip {
            color: #999;
          }
          &.is-checked {
            border-color: #3870EA;
            .el-radio__label {
              color: #3870EA;
            }
          }
        }
      }
    }

    /*商品品类*/
    /deep/ .dialog-category {
      .el-dialog__header {
        padding: 15px;
        border-bottom: solid 1px #e6e6e6;
      }
      .el-dialog__body {
        padding: 15px;
      }
      .goods-category {
        display: flex;
        height: 380px;
        border: 1px solid #e6e6e6;
        background: #fafafa;
        & > ul {
          display: inline-block;
          padding: 8px 4px 8px 8px;
          margin: 0;
          list-style: none;
          width: 33.3333%;
          background: none repeat  0 0 #fff;
          border-right: 1px solid #e6e6e6;
          letter-spacing: normal;
          vertical-align: top;
          overflow-y: auto;
          word-spacing: normal;
          li {
            line-height: 20px;
            padding: 5px;
            cursor: pointer;
            color: #333;
            font-size: 12px;
            display: flex;
            flex-wrap: nowrap;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
          }
          &:nth-child(3) {
            border-right: none;
          }
        }
      }
    }

    /** 当前品类被选中的样式 */
    .activeClass {
      background-color: #d9edf7;
      border: 1px solid #bce8f1;
      color: #3a87ad;
    }

    /*!*当前选择的商品品类文字*!*/
    .current-goods-category {
      text-align: left;
      padding: 0;
      width: 100%;
      color: #333;
      margin: 10px auto;
      font-size: 13px;
      span {
        color: #999;
      }
    }
  }

  /*编辑基本信息*/
  .el-form {
    padding-bottom: 80px;
    .el-form-item {
      width: 100%;
      text-align: left;
    }
  }

  /*平铺*/
  div.base-info-item>div {
    margin-left: 5%
  }
  div.base-info-item {
    h4 {
      margin-bottom: 10px;
      padding: 0 10px;
      line-height: 38px;
      text-align: left;
      // border: 1px solid #ddd;
      background-color: #f8f8f8;
      font-weight: bold;
      color: #333;
      font-size: 14px;
    }

    /** 审核信息-拒绝原因 */
    .auth-info {
      color: red;
    }

    .el-form-item {
      width: 30%;
      min-width: 300px;
    }
    .goods-name-width {
      width: 50%;
      min-width: 300px;
    }
    .goods-selling-width {
      width: 50%;
      min-width: 300px;
    }
    .el-form-item__content {
      margin-left: 120px;
      text-align: left;
    }
    .video_box {
      position: relative;
      width: 100px;
      height: 100px;
      .delet-list-item {
        position: absolute;
        top: -10px;
        right: -10px;
        height: 18px;
        width: 18px;
        line-height: 18px;
        border-radius: 50%;
        text-align: center;
        cursor: pointer;
        background: rgba(0, 0, 0, .5);
        color: #fff;
      }
    }
    /deep/ .img-upload {
      .el-upload--picture-card {
        padding: 0;
        width: auto;
        height: auto;
        border: none;
      }
      .el-upload-list__item,
      .progress{
        position: relative;
        padding: 0;
        margin: 0 10px 0 0;
        width: 100%;
        height: 100%;
        line-height: 0;
        border: dashed 1px #E6E6E6;
        border-radius: 2px;
        text-align: center;
        overflow: hidden;
        box-sizing: border-box;
        background: #F8FAFF;
        color: #999;
        margin-bottom: 50px;
      }
      .el-upload-list__item,
      .img_none {
        position: relative;
        padding: 0;
        margin: 0 10px 0 0;
        width: 100px;
        height: 100px;
        line-height: 0;
        border: dashed 1px #E6E6E6;
        border-radius: 2px;
        text-align: center;
        overflow: hidden;
        box-sizing: border-box;
        background: #F8FAFF;
        color: #999;
      }
      .img_none {
        padding: 15px;
        .el-icon-upload2 {
          font-size: 42px;
        }
        .upload-tip {
          line-height: 20px;
        }
      }
      .el-upload__tip {
        line-height: 20px;
        color: #999;
        font-size: 14px;
      }
      &.upload-video {
        line-height: 0;
        .el-upload {
          position: relative;
        }
        video {
          width: 100px;
          height: 100px;
          line-height: 0;
          border: dashed 1px #E6E6E6;
          background: #F8FAFF;
        }
      }
    }
    .is-error {
      .img_none {
        border-color: #F56C6C;
      }
    }
    p.goods-group-manager {
      padding-left: 7.5%;
      text-align: left;
      color: #999;
      font-size: 13px;
    }

    .category-none {
      display: inline-block;
      padding: 0 15px;
      height: 32px;
      line-height: 30px;
      min-width: 180px;
      background-color: #fff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      cursor: pointer;
      color: #606266;
    }
    .category-show {
      color: #333;
      .eidt-category {
        color: #3870EA;
        cursor: pointer;
      }
    }
    .row-tip {
      margin-top: 10px;
      line-height: 20px;
      color: #999;
      font-size: 14px;
    }

    /*teatarea*/
    /deep/ .el-textarea {
      width: 150%;
    }
    .seo-text {
      width: 150%;
    }
  }

  /*折叠面板*/
  .el-collapse-item {
    /deep/ .el-collapse-item__header {
      text-align: left;
      background-color: #f8f8f8;
      padding:0 10px;
      font-weight: bold;
      color: #333;
      font-size: 14px;
    }
    .el-form-item {
      margin-left: 5%;
      width: 25%;
    }
    /deep/ .el-form-item__content {
      margin-left: 120px;
      text-align: left;
    }
    p.goods-group-manager {
      padding-left: 12%;
      text-align: left;
      color: #999;
    }
    /deep/ .el-collapse-item__content {
      padding: 10px 0;
      text-align: left;
    }
  }

  /*商品描述*/
  .goods-intro {
    line-height: 40;
  }

  /** 底部步骤 */
  // .footer {
  // }

  /*图片上传组件第一张图设置封面*/
  .goods-images {
    /deep/ li.el-upload-list__item:first-child {
      position: relative;
    }
    /deep/ li.el-upload-list__item:first-child:after {
      content:"封";
      color:#fff;
      font-weight:bold;
      font-size: 12px;
      position: absolute;
      left: -15px;
      top: -6px;
      width: 40px;
      height: 24px;
      padding-top: 6px;
      background: #13ce66;
      text-align: center;
      -webkit-transform: rotate(-45deg);
      transform: rotate(-45deg);
      -webkit-box-shadow: 0 0 1pc 1px rgba(0,0,0,.2);
      box-shadow: 0 0 1pc 1px rgba(0,0,0,.2);
    }
  }

  .link-btn {
    margin-left: 5px;
    color: #3870EA;
    cursor: pointer;
  }
  .el-popover {
    padding: 10px;
    line-height: 0;
    .popover-head {
      padding-bottom: 10px;
      line-height: 20px;
      color: #333;
      font-size: 14px;
    }
    .popover-img {
      width: 100%;
    }
  }
  .checkWeekTime{
    display: flex;
    flex-flow: row;
  }
</style>
<style type="text/scss" lang="scss">
  .el-form-item__label{
    word-break: break-all;
  }
  .el-progress-circle{
    width: 100% !important;
  }
</style>
